package com.ouyunc.oauth2.config.override;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ouyunc.common.constant.Auth2Constant;
import com.ouyunc.common.constant.enums.ResponseCodeEnum;
import com.ouyunc.common.base.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class IOAuth2AuthenticationEntryPoint  extends OAuth2AuthenticationEntryPoint {
    private static final Logger log = LoggerFactory.getLogger(IOAuth2AuthenticationEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.error("认证异常了: {}",e.getMessage());
        if (StringUtils.isBlank(request.getParameter(Auth2Constant.CLIENT_SECRET))) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(ResponseCodeEnum.BAD_REQUEST.code());
            response.getWriter().print(JSON.toJSONString(ResponseResult.error(ResponseCodeEnum.BAD_REQUEST, "缺少参数: client_secret！"), SerializerFeature.WriteMapNullValue));
        }else {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(ResponseCodeEnum.UNAUTHORIZED.code());
            response.getWriter().print(JSON.toJSONString(ResponseResult.error(ResponseCodeEnum.UNAUTHORIZED,"Bad credentials"), SerializerFeature.WriteMapNullValue));
        }
    }
}
